<template>
    <div class="car">
        <template v-if="isLogin">
            <div class="car-list">
                <van-swipe-cell v-for="item in list" :key="item.cartid" class="list-item">
                    <van-checkbox @change="changeHandler(item.cartid, $event)" v-model="item.flag"></van-checkbox>
                    <van-card class="goods-card" :title="item.proname" :price="(item.originprice * item.discount) / 10"
                        :thumb="item.img1">
                        <template v-slot:num>
                            <van-stepper v-model="item.num" theme="round" @change="addHandler(item.cartid, item.num)"
                                button-size="22" disable-input />
                        </template>
                    </van-card>
                    <template #right>
                        <!-- -->
                        <div class="del">
                            <van-button square text="删除" type="danger" class="delete-button" />
                        </div>
                    </template>
                </van-swipe-cell>
            </div>
            <van-submit-bar class="order" :price="allPrice" button-text="提交订单" @submit="submitHandler">
                <van-checkbox v-model="checkAll">全选</van-checkbox>
            </van-submit-bar>
        </template>
        <template v-else>
            <div class="login-tips">
                <span>登录后可同步账户购物车中的商品</span>
                <van-button class="btn" size="small" color="#f52d12" @click="toLogin">登录</van-button>
            </div>
            <van-empty
                image="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png"
                image-size="80" description="登录后可同步购物车中商品" />
        </template>
    </div>
</template>

<script setup>
import { ref, computed, watchEffect } from "vue";
import { storeToRefs } from "pinia";
import { useRouter, useRoute } from 'vue-router';
import { showFailToast, showSuccessToast, showToast } from 'vant';

import { getCartListAPI, updateCartAllCheckedStatusAPI, updateCartOneCheckedStatusAPI, updateCartNumAPI, delCartByIdAPI } from "@/api/cart.js";
import { addOrderAPI } from "@/api/order.js";
import { useUserStore } from "@/stores/user.js"

let router = useRouter();
let route = useRoute();
let User = useUserStore();
let { isLogin, userid } = storeToRefs(User);

let list = ref([]);


let checkAll = computed({
    get: function () {
        var flag = list.value.every(item => item.flag);
        return list.value.length > 0 ? flag : false;
    },
    set: function (val) {
        list.value.forEach(item => item.flag = val);
    }
})
let allPrice = computed(() => {
    return list.value.reduce((prev, item) => {
        if (item.flag) {
            prev += (item.originprice * item.discount) / 10 * item.num;
        }
        return prev;
    }, 0).toFixed(2) * 100;
})

let getCartList = async () => {
    try {
        var res = await getCartListAPI({
            userid: userid.value,
        });
        console.log("购物车查询成功", res);
        list.value = res.data;
    } catch (err) {
        showFailToast(err.message);
    }
}

let changeHandler = async (cartid, flag) => {
    console.log(11111, flag);
    try {
        var res = await updateCartOneCheckedStatusAPI({
            cartid,
            flag,
        });
        console.log("状态更新成功", res);
    } catch (err) {
        showFailToast(err.message);
    }

}
let addHandler = async (cartid, num) => {
    console.log(11111, num);
    try {
        var res = await updateCartNumAPI({
            cartid,
            num,
        });
        console.log("数量更新成功", res);
    } catch (err) {
        showFailToast(err.message);
    }

}
let submitHandler = async () => {
    var num = list.value.filter(item => item.flag).length; // 找到选中的商品数量
    console.log("num",num);
    if (num > 0) {
        try {
            var res = await addOrderAPI({
                userid:userid.value
            });
            console.log("新增成功", res);

            router.push({name:'order',query:{time:res.time}});
        } catch (err) {
            showFailToast(err.message);
        }
    } else {
        showFailToast("您还未选中任何商品!")
    }


}

watchEffect(() => {
    getCartList();
})



</script>

<style lang="scss" scoped>
.login-tips {
    height: 1.2rem;
    display: flex;
    justify-content: center;
    align-items: center;

    .btn {
        margin-left: 0.1rem;
    }
}

.list-item {
    :deep(.van-swipe-cell__wrapper) {
        display: flex;

    }

    .goods-card {
        flex: 1;
        margin-top: 0;
        background: none;
        padding-left: 0.1rem;

    }

    .del {
        display: block;
        background-color: #f2380c;
        // color: #fff;
        width: 1rem;
        height: 100%;
    }

}

.order {
    margin-bottom: 1rem;
}
</style>